<template>
  <div style="width: 100%; overflow: hidden">
    <div class="top">信息详情</div>
    <el-image style="width: 100%" :src="info?.eventImg" fit="contain" />
    <div style="width: 100%">
      <div id="players"></div>
      <el-row>
        <el-form>
          <el-form-item>
            <!--  @change="arrangeWindow" -->
            <el-radio-group v-model="splitNum"> </el-radio-group>
            <el-button @click="wholeFullScreen" v-show="!isMoveDevice"
              >整体全屏</el-button
            >&nbsp;
          </el-form-item>
        </el-form>
        <el-form
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          v-show="tabActive !== 'log'"
        >
          <el-form-item class="layout">
            <el-button
              id="btn-playback"
              @click="playbackStart"
              :loading="buttonLoading"
              >开始回放</el-button
            >
            <el-button id="btn-playback-pause" @click="playbackPause"
              >暂停</el-button
            >
            <el-button id="btn-playback-sesume" @click="playbackResume"
              >恢复</el-button
            >
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <div class="content">
      <div>
        报警地点：<span>{{ info?.monitorName }}</span>
      </div>
      <div style="margin-top: 20px">
        抓拍时间：<span>{{ info?.eventTime }}</span>
      </div>
      <div>
        报警时间：<span>{{ info?.createdAt }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getSingleWarningList } from "@/api/preWarning";
import Video from "../video/index.vue";
import { formatTime, timeToMs } from "../index/indexTableConfig";
import dayjs from "dayjs";
interface HostGlobal extends Window {
  /** 引入的海康监控 */ JSPlugin: any;
}
const hostGlobal: HostGlobal = window as any;

const id = useRoute().query?.id as any;
const info = ref();
const splitNum = ref(1);
let player: any = null;
const buttonLoading = ref(false);
const IS_MOVE_DEVICE = false; // 是否移动设备
const MSE_IS_SUPPORT = true; // 是否支持mse
const params = {
  url: "",
  startTIme: "",
  endTime: "",
  point: "",
  rate: 0,
};
const tabActive = MSE_IS_SUPPORT ? "mse" : "decoder";
const labelCol = { span: 5 };
const wrapperCol = { span: 18 };
const urls = ref({
  realplay: "",
  talk: "wss://10.41.163.126:6014/proxy/10.41.163.126:559/EUrl/6gFx47S",
  playback: "ws://ydriver-car-image.cyberstone.com.cn:559/openUrl/Ycmq67C",
});
/**全屏 */
const wholeFullScreen = () => {
  player.JS_FullScreenDisplay(true).then(
    () => {
      console.log(`wholeFullScreen success`);
    },
    (e: any) => {
      console.error(e);
    }
  );
};
const isMoveDevice = IS_MOVE_DEVICE;

function playbackStart() {
  buttonLoading.value = true;

  const tzstart = params.startTIme;
  const tzend = params.endTime;

  const { playURL, mode, index, startTime, endTime } = {
    playURL: params.url,
    mode: 0,
    index: 0,
    startTime: tzstart,
    endTime: tzend,
  };

  player.JS_Play(playURL, { playURL, mode }, index, startTime, endTime).then(
    () => {
      console.log("playbackStart success");
      buttonLoading.value = false;
      params.rate = 1;
    },
    (e: any) => {
      console.error(".....", e);
      buttonLoading.value = false;
    }
  );
}
/**
 * 格式化日期
 */
function formatDate(date: Date | string, fmt = "yyyy-MM-dd"): string {
  if (!date) return "";
  if (typeof date === "string") {
    date = new Date(date);
  }
  let out = fmt;
  const o: { [key: string]: number } = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };

  if (/(y+)/.test(fmt)) {
    out = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }

  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      out = (out as any).replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
      );
    }
  }
  return out;
}

/**
 * 显示日期-时间
 * - smaller yyyy-MM-dd
 * - short yyyy-MM-dd hh:mm
 * - long yyyy-MM-dd hh:mm:ss
 * - point yyyy.MM.dd hh:mm:ss
 * - year yyyy
 */
function date(
  date: Date,
  mode: "smaller" | "short" | "long" | "point" | "year" | "line"
) {
  switch (mode) {
    case "smaller":
      return formatDate(date, "yyyy-MM-dd");
    case "short":
      return formatDate(date, "yyyy-MM-dd hh:mm");
    case "long":
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    case "point":
      return formatDate(date, "yyyy.MM.dd hh:mm:ss");
    case "line":
      return formatDate(date, "yyyy/MM/dd hh:mm:ss");
    case "year":
      return formatDate(date, "yyyy");
  }
}

onMounted(async () => {
  if (id) {
    const res = await getSingleWarningList(id);
    info.value = res;

    const u = navigator.userAgent;
    let beginTime, endTime;
    if (u.indexOf("iPhone") > -1) {
      const date1 = new Date(
        Date.parse(res.eventTime.replace(/\-/g, "/")) - 30000
      ) as any;
      const date2 = new Date(
        Date.parse(res.eventTime.replace(/\-/g, "/")) + 30000
      ) as any;
      const bTime = date(date1, "line");
      const eTime = date(date2, "line");
      function handleTime(time: string) {
        return (
          time.replace(/\//g, "-").slice(0, 10) +
          "T" +
          time.slice(11) +
          ".000+08:00"
        );
      }
      beginTime = handleTime(bTime);
      endTime = handleTime(eTime);
    } else {
      const date1 = new Date(Date.parse(res.eventTime) - 30000) as any;
      const date2 = new Date(Date.parse(res.eventTime) + 30000) as any;
      const bTime = date(date1, "long");
      const eTime = date(date2, "long");
      beginTime = bTime.slice(0, 10) + "T" + bTime.slice(11) + ".000+08:00";
      endTime = eTime.slice(0, 10) + "T" + eTime.slice(11) + ".000+08:00";
    }
    const pointName = res.monitorName;
    const data = (
      await axios.post(
        "https://hik-api-proxy.cyberstone.com.cn/proxy/videoV2CamerasPlaybackURLs",
        {
          beginTime,
          endTime,
          pointName,
          withNvr: false,
          type: "wss",
        }
      )
    )?.data?.data;
    params.url = data?.url;
    params.endTime = endTime;
    params.startTIme = beginTime;
    params.point = pointName;
    createPlayer();
    setTimeout(() => {
      playbackStart();
    }, 200);
  }
  // previewURLs();
  const dom = document.querySelector("#players") as HTMLDivElement;
  dom.style.setProperty("--window-width", document.body.clientWidth + "px");
});

function playbackPause() {
  player.JS_Pause().then(
    () => {
      console.log("playbackPause success");
    },
    (e: any) => {
      console.error(e);
    }
  );
}
function playbackResume() {
  player.JS_Resume().then(
    () => {
      console.log("playbackResume success");
    },
    (e: any) => {
      console.error(e);
    }
  );
}
const createPlayer = () => {
  player = new hostGlobal.JSPlugin({
    szId: "players",
    szBasePath: "/public-assets/static/",
    iMaxSplit: 4,
    // iCurrentSplit: IS_MOVE_DEVICE ? 1 : 2,
    iCurrentSplit: 1,
    openDebug: true,
    oStyle: {
      borderSelect: IS_MOVE_DEVICE ? "#000" : "#FFCC00",
    },
  });

  // 事件回调绑定
  player.JS_SetWindowControlCallback({
    windowEventSelect: function (iWndIndex: any) {
      //插件选中窗口回调
      console.log("windowSelect callback: ", iWndIndex);
    },
    pluginErrorHandler: function (
      iWndIndex: any,
      iErrorCode: any,
      oError: any
    ) {
      //插件错误回调
      console.log("pluginError callback: ", iWndIndex, iErrorCode, oError);
    },
    windowEventOver: function () {
      //鼠标移过回调
      //console.log(iWndIndex);
    },
    windowEventOut: function () {
      //鼠标移出回调
      //console.log(iWndIndex);
    },
    windowEventUp: function () {
      //鼠标mouseup事件回调
      //console.log(iWndIndex);
    },
    windowFullCcreenChange: function (bFull: any) {
      //全屏切换回调
      console.log("fullScreen callback: ", bFull);
    },
    firstFrameDisplay: function (iWndIndex: any, iWidth: any, iHeight: any) {
      //首帧显示回调
      console.log("firstFrame loaded callback: ", iWndIndex, iWidth, iHeight);
    },
    performanceLack: function () {
      //性能不足回调
      console.log("performanceLack callback: ");
    },
  });
};
</script>

<style lang="scss">
.top {
  height: 42px;
  line-height: 42px;
  background-color: #0084ff;
  color: #fff;
  text-align: center;
}
#players {
  width: var(--window-width) !important;
  height: calc(var(--window-width) * 3 / 4) !important;
  .sub-wnd {
    width: 100% !important;
    height: 100% !important;
  }
  #players_canvas_draw0,
  #players_playCanvas0 {
    width: 200% !important;
    height: 200% !important;
  }
}
.content {
  padding: 20px;
}
</style>
